<template>
	<basic-container>
		<avue-crud :option="option" :data="data" ref="crud" v-model="form" :table-loading="loading" :permission="permissionList"
		 @search-change="searchChange" :page="page" @refresh-change="refreshChange" @search-reset="searchReset"
		 @current-change="currentChange" @size-change="sizeChange" @on-load="onLoad">
			<!-- 搜索自定义 -->
			<template slot="search">
				<el-col :span="12">
					<el-form-item label="商品分类" style="display: inline-block;width: 50%;">
						<el-cascader v-model="productData" :options="chooseProductOption" size="mini" @change="handleChange"></el-cascader>
					</el-form-item>
					<el-form-item label="本店分类" label-width="100px"  style="display: inline-block;width: 50%;">
						<el-cascader v-model="productUserData" :options="chooseProductUserOption" size="mini" @change="handleUserChange"></el-cascader>
					</el-form-item>
				</el-col>
			</template>


			<!--暂时不要-->
			<!--      <template slot="search">-->
			<!--        <el-form-item label="价格">-->
			<!--          <el-col :span="8">-->
			<!--            <el-input placeholder="最低价"-->
			<!--                      size="small"-->
			<!--                      v-model="searchForm.goodsPrice" />-->
			<!--          </el-col>-->
			<!--          <el-col class="line"-->
			<!--                  :span="2"-->
			<!--                  style="text-align:center">—</el-col>-->
			<!--          <el-col :span="8">-->
			<!--            <el-input placeholder="最高价"-->
			<!--                      size="small"-->
			<!--                      v-model="searchForm.showPrice" />-->
			<!--          </el-col>-->
			<!--        </el-form-item>-->
			<!--      </template>-->
			<!-- 操作栏自定义 -->
			<template slot-scope="scope" slot="menu">
				<el-button v-if="goodsStatus == 2 " icon="el-icon-view" type="text" size="small" @click="lookOver(scope.row.id)">查看</el-button>
				<!--activityStatus为true时是商品没参加活动呢，false时是已经参加活动了-->
				<el-button v-if="goodsStatus != 2 && scope.row.activityStatus " type="text" icon="el-icon-edit" @click="viewGoodsDetail(scope.row.id)"
				 size="small">编辑</el-button>
				<el-button v-if="goodsStatus == 0 " type="text" icon="el-icon-edit" @click="editalStock(scope.row.id)" size="small">编辑库存</el-button>
				<el-button v-if="goodsStatus == 1 " @click="upperOrlower(scope.row.id,0)" type="text" size="small">上架</el-button>
				<el-button v-if="goodsStatus == 0 " @click="upperOrlower(scope.row.id,1)" type="text" size="small">下架</el-button>
				<el-button v-if="goodsStatus == 3 " @click="checkReasons(scope.row.id)" type="text" size="small">查看原因</el-button>
			</template>
			<template slot-scope="{row}" slot="goodsMainPhotoUrl">
				<img :src="row.goodsMainPhotoUrl" style="width:50px;height:50px;" />
			</template>
			<template slot-scope="{row}" slot="storeRecommend">
				<el-switch @change="rowSwitchChange(row)" v-model="row.storeRecommend"></el-switch>
			</template>
		</avue-crud>
		<el-dialog title="审核拒绝原因" :visible.sync="resionView" width="40%">
			<div color="#fff" style="border: none;color: #333333;min-height: 200px;height: auto;width:100%;">{{refuseResion}}</div>
			<span slot="footer">
				<el-button type="primary" size="small" @click="closeResion">关闭</el-button>
			</span>
		</el-dialog>
		<el-drawer title="商品详情" size="80%" :withHeader=false :visible.sync="dialogTableVisible">
			<add-goods v-if="dialogTableVisible" :disadledSpec="disadledSpec" :goodsId="goodsId" :isPublish="isPublish" :isCheck="isCheck"
			 :isRedact="isRedact"></add-goods>
		</el-drawer>
		<el-drawer title="库存列表" size="60%" :visible.sync="stockVisible" :destroy-on-close='true' @close="closeDrawer" >
			<div style="padding: 20px;">
				<avue-crud :option="optionStock" :data="stockData" ref="stockCrud" v-model="stockForm" :table-loading="stockLoading"
				 :permission="permissionList" @refresh-change="refreshStockChange">
					<template slot-scope="scope" slot="menu">
						<el-button @click="editStock(scope.row)" type="text" size="small">编辑库存</el-button>
					</template>
				</avue-crud>
			</div>
		</el-drawer>
		<el-dialog title="库存详情" :visible.sync="stockView" :before-close="handleEmpty" width="40%">
			<avue-form ref="stockRef" v-model="stockDetail" :option="stockDetailOption">
				<template slot="skuName">
					<el-tag color="#fff"
					        style="border: none;color: #333333;white-space: pre-wrap;line-height: 24px;;padding-top: 6px;height: auto;">{{stockDetail.skuName}}</el-tag>
				</template>
				<template slot="stocks">
					<el-tag color="#fff"
					        style="border: none;color: #333333;">{{stockDetail.stocks}}</el-tag>
				</template>
				<template slot="remindStock">
					<el-tag color="#fff"
							style="border: none;color: #333333;">{{stockDetail.remindStock}}</el-tag>
				</template>
				<template slot="tightInventory">
					<el-tag color="#fff"
							style="border: none;color: #333333;">{{stockDetail.tightInventory}}</el-tag>
				</template>
				<template slot="menuForm">
					<el-button type="primary" @click="handleSubmit">提 交</el-button>
					<el-button @click="handleEmpty">取消</el-button>
				</template>
			</avue-form>
		</el-dialog>
	</basic-container>
</template>

<script>
	import {
		getList,
		getGoodsClassAll,
		getUserGoodsClassAll,
		updateDisplay,
		upperOrlower,
		checkReasons,
		showGoodsStock,
		editGoodsStock
	} from "@/api/base/goods/seller/goods";
	import {
		mapGetters
	} from "vuex";
	import addGoods from '@/views/base/goods/seller/addGoods';
	export default {
		props: ["goodsStatus"],
		data() {
			return {
				stockDetailOption: {
					emptyBtn: false,
					submitBtn: false,
					labelWidth:130,
					column: [{
						label: "规格",
						prop: "skuName",
						span:24,
						formslot:true,
					}, {
						label: "现有库存",
						prop: "stocks",
						span:24,
						formslot:true,
					}, {
						label: "调整库存",
						prop: "num",
						span:24,
						rules: [{
							required: true,
							message: "请输入库存",
							trigger: "blur"
						}],
					},{
						label: "提醒库存量",
						prop: "remindStock",
						span:24,
						rules: [{
							required: true,
							message: "请输入提醒库存量",
							trigger: "blur"
						}],
					} ,{
						label: "提醒库存紧张数",
						prop: "tightInventory",
						span:24,
						rules: [{
							required: true,
							message: "请输入提醒库存紧张数",
							trigger: "blur"
						}],
					} ]
				},
				stockDetail: {},
				isPublish: false,
				isCheck: false,
				isRedact: false,
				disadledSpec: false,
				goodsId: "",
				dialogTableVisible: false,
				refuseResion: "",
				resionView: false,
				searchForm: {},
				stockVisible: false,
				optionStock: {
					size: "mini",
					excelBtn: false,
					tip: false,
					addBtn: true,
					border: true,
					index: false,
					selection: false,
					editBtn: false,
					viewBtn: false,
					delBtn: false,
					searchBtn: false,
					refreshBtn: false,
					columnBtn: false,
					rowKey: "skuId",
					// calcHeight: 380,80,
					dialogType: "dialog",
					align: 'center',
					column: [{
						label: "规格",
						prop: "skuName",
					}, {
						label: "单价",
						prop: "price",
					}, {
						label: "库存",
						prop: "stocks",
						type: 'number',
					},
					{
						label: "提醒库存数",
						prop: "remindStock",
						type: 'number',
					},
					{
						label: "提醒库存紧张数",
						prop: "tightInventory",
						type: 'number',
					}]
				},
				stockLoading: false,
				stockForm: {},
				stockData: [],
				chooseProductOption: [],
				productData: [],
				chooseProductUserOption:[],
				productUserData:[],
				form: {
					goodsPrice: ""
				},
				query: {},
				addForm: {
					goodsInventory: ""
				},
				multipleSelection: [],
				addDialog: false,
				loading: true,
				rolesTree: [],
				classData: [],
				cascaderProps: {
					id: "id",
					label: "className",
					children: "childrenNodes"
				},
				classList: [],
				rolesKeys: [],
				box: false,
				data: [],
				ParentGoods: [],
				// 选中的父级分类id数组
				selectedKeys: [],
				page: {
					pageSize: 10,
					currentPage: 1,
					total: 0
				},
				option: {
					size: "mini",
					excelBtn: false,
					tip: false,
					addBtn: true,
					border: true,
					index: false,
					selection: false,
					editBtn: false,
					viewBtn: false,
					delBtn: false,
					searchBtn: false,
					refreshBtn: false,
					columnBtn: false,
					rowKey: "id",
					dialogType: "dialog",
					menuWidth: 180,
					menuAlign:"center",
					align: "center",
					searchMenuSpan:8,
					column: [{
							label: "商品名称",
							prop: "goodsName",
							align:'left',
							fixed:true,
							search: true,
							width: 250,
							rules: [{
								required: true,
								message: "请输入商品名称",
								trigger: "blur"
							}]
						}, {
							label: "商品图片",
							prop: "goodsMainPhotoUrl",
							width:150,
							slot: true,
							rules: [{
								required: true,
								message: "请输入主图片",
								trigger: "blur"
							}]
						},

						{
							label: "商品分类",
							prop: "goodsClassId",
							dicUrl: "base/sellerGoodsClass/listDicData",
							props: {
								label: "label",
								value: "value"
							},
							rules: [{
								required: true,
								message: "请输入分类",
								trigger: "blur"
							}]
						},

						{
							label: "本店分类",
							prop: "userGoodsClassId",
							dicUrl: "base/sellerUserGoodsClass/listDicData",
							props: {
								label: "label",
								value: "value"
							},
							rules: [{
								required: true,
								message: "请输入分类",
								trigger: "blur"
							}]
						},

						{
							label: "库存量",
							prop: "stock",
							rules: [{
								required: true,
								message: "请输入商品价格",
								trigger: "blur"
							}]
						},
						{
							label: "商城售价(￥)",
							prop: "showPrice",
							fixed: true,
							width:150,
							rules: [{
								required: true,
								message: "请输入商城售价",
								trigger: "blur"
							}]
						},
						//卖家商品列表页面展示的“推荐”是店铺是否推荐，编辑页面的单选按钮“商品推荐”，也是店铺是否推荐 storeRecommend
						{
							label: "推荐",
							prop: "storeRecommend",
							slot: true,
							width: 100,
						},
						{
							label: "权重",
							prop: "goodsSort",
						},
						{
							label: "是否为跨域商品",
							prop: "isCrossBorderGood", 
							type:'select',
							dicData:[{
								value:true,
								label:'是'
							},{
								value:false,
								label:'否'
							}]
						}
					]
				},
				goodId: '',
				stockView: false,
				stock: '',
				goodsStockFlag: true,
			};
		},
		components: {
			addGoods
		},
		mounted() {
			this.$EventBus.$on('finishhandle', (bool) => {
				if (this.data.length == 1) {
					this.page.currentPage -= 1
				}
				this.onLoad(this.page);
				this.dialogTableVisible = !bool
			})
		},
		computed: {
			...mapGetters(["permission", "userInfo"]),
			permissionList() {
				return {
					addBtn: this.vaildData(
						this.permission["/mall-cloud-base/sellerGoods/addItem"],
						false
					),
				};
			}
		},
		created() {
			getGoodsClassAll().then(res => {
				if (res.data.code == 200 && res.data.data) {
					this.chooseProductOption = res.data.data;
				}
			});

			getUserGoodsClassAll().then(res => {
				if (res.data.code == 200  && res.data.data) {
					this.chooseProductUserOption = res.data.data;
				}
			});

			this.onLoad(this.page, {});
		},
		methods: {
			//编辑库存 打开库存列表
			editalStock(goodId) {
				this.goodId = goodId
				this.onStockLoad();
				this.stockVisible = true
			},
			//编辑单条库存
			editStock(row) {
				this.stockView = true
				this.stockDetail = row
				console.log(row)
				this.stock = row.stocks
			},
			//编辑库存提交
			handleSubmit() {
				let re = /^-?[1-9]+[0-9]*$|^0$/;
				let re1 = /^[1-9]+[0-9]*$|^0$/;
				if(this.stockDetail.num==''){
					this.$message.error( "请输入调整库存！");
					return;
				}
				if (!re.test(this.stockDetail.num)) {
					this.$message.error( "调整库存量必须为整数");
					return;
				}
				if (!re1.test(this.stockDetail.remindStock)) {
					this.$message.error( "提醒库存量必须为正整数");
					return;
				}
				if (!re1.test(this.stockDetail.tightInventory)) {
					this.$message.error( "提醒库存紧张数必须为正整数");
					return;
				}

				let lastStocks=Number(this.stockDetail.num) +this.stockDetail.stocks
				if(lastStocks<0){
					this.$message.error( "减去的库存值不能大于现有库存!");
					return;
				}
				//防止重复提交
				if (this.goodsStockFlag) {
					this.goodsStockFlag = false;
				} else {
					return false;
				}
				let num=Number(this.stockDetail.num)
				let type='add'
				if(num<0){
					type='subtract'
					num= -this.stockDetail.num
				}
				if(num>100000){
					this.$message.error( "调整库存不能超过100000！");
					this.goodsStockFlag=true
					return;
				}
				let data={
					isAddOrSubtract:type,
					count:num,
					skuId: this.stockDetail.skuId,
					remindStock:this.stockDetail.remindStock,
					tightInventory:this.stockDetail.tightInventory
				}
				editGoodsStock(data).then(res => {
					if(res.data.code==200){
						this.onStockLoad();
						this.$message({
						  type: "success",
						  message: "修改成功!"
						});
					}else{
						this.$message.error(res.data.message);
					}
					setTimeout(()=>{
						this.goodsStockFlag = true;
					},1000)
				});
				this.handleEmpty()
				this.onLoad(this.page);
			},
			handleEmpty() {
				this.stockView = false
				this.$refs.stockRef.resetForm()
				this.$refs.stockRef.clearValidate()
				this.stockDetail={}
			},
			viewGoodsDetail(id) { //编辑
				this.goodsId = id
				this.isRedact = true //编辑
				this.disadledSpec = true //编辑时候禁用选规格
				this.dialogTableVisible = true
			},
			lookOver(id) {
				//查看
				this.goodsId = id;
				this.isCheck = true;
				this.dialogTableVisible = true;
			},
			//关闭原因框
			closeResion() {
				this.resionView = false;
			},
			//查看拒绝原因
			checkReasons(id) {
				checkReasons(id).then(res => {
					if (res.status == 200 && res.data.code == 200) {
						this.refuseResion = res.data.data;
						this.resionView = true;
					} else {
						this.$message.error(res.data.message);
					}

				});
			},
			upperOrlower(id, status) {
				this.loading = true;
				if(status==0){
					upperOrlower(id, status).then(res => {
						this.loading = false;
						if (res.status == 200 && res.data.code == 200) {
							//如果当前不是第一页并且最后一页剩余一条数据(解决最后一页删除完后还查询最后一页后导致空白的问题)
							if(this.page.currentPage>1 && this.page.total%this.page.pageSize==1){
								this.page.currentPage=this.page.currentPage-1;
							}
							this.$message.success("操作成功！");
							this.onLoad(this.page, this.query);
							if (status == 0) {
								this.$emit('flush-list', 'first')
							} else {
								this.$emit('flush-list', 'second')
							}
					
						} else {
							this.$message.error(res.data.message);
						}
					
					});
				}else{
					this.loading = false;
					this.$confirm("确定下架该商品吗?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						this.loading = true;
						upperOrlower(id, status).then(res => {
							this.loading = false;
							if (res.status == 200 && res.data.code == 200) {
								//如果当前不是第一页并且最后一页剩余一条数据(解决最后一页删除完后还查询最后一页后导致空白的问题)
								if(this.page.currentPage>1 && this.page.total%this.page.pageSize==1){
									this.page.currentPage=this.page.currentPage-1;
								}
								this.$message.success("操作成功！");
								this.onLoad(this.page, this.query);
								if (status == 0) {
									this.$emit('flush-list', 'first')
								} else {
									this.$emit('flush-list', 'second')
								}
						
							} else {
								this.$message.error(res.data.message);
							}
						});
					})
				}
			},
			refreshStockChange() {
				this.onStockLoad();
			},
			onStockLoad() {
				showGoodsStock(this.goodId).then(res => {
					this.stockData = res.data.data
				})
				this.stockLoading = false;
			},
			searchChange(params,done) {
				this.page.currentPage = 1
				this.$refs.crud.toggleSelection();
                if (this.productData != undefined) {
                    if(this.productData.length == 0){
                        params.goodsClassId ="";
                    }

                }

                if(this.productUserData != undefined){
                    if(this.productUserData.length == 0){
                        params.userGoodsClassId = "";
                    }
                }
				this.query = params;
				this.onLoad(this.page, params,done);
			},
			searchReset() {
				this.query = {};
				this.$refs.crud.toggleSelection();
				this.searchForm = {};
				this.productData = [];
				this.productUserData = [];
				this.onLoad(this.page);
			},
			// 选择项发生变化触发函数
			selectChange() {},
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
				this.onLoad(this.page);
			},
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
				this.onLoad(this.page);
			},
			refreshChange() {
				this.onLoad(this.page);
			},
			onLoad(page, params = {},done) {
				params.goodsStatus = this.goodsStatus;
				if (this.productData != undefined) {
					if(this.productData.length>0){
						params.goodsClassId = this.productData[this.productData.length-1];
					}

				}

				if(this.productUserData != undefined){
					if(this.productUserData.length>0){
						params.userGoodsClassId = this.productUserData[this.productUserData.length-1];
					}
				}

				this.loading = true;

				getList(
					page.currentPage,
					page.pageSize,
					Object.assign(params, this.query)
				).then(res => {
					if(done){
						done();
					}
					this.loading = false;
					const data = res.data;
					this.page.total = data.count;
					if (res.status == 200) {
						this.data = data.data.map(item => {
							item["originalPrice"] = item.goodsPriceBean.originalPrice;
							item["showPrice"] = item.showPrice;
							return item;
						});
						console.log(this.data)
					}
				});
			},
			rowSwitchChange(row) {
				if (row.storeRecommend) {
					updateDisplay(row.id, "true");
				} else {
					updateDisplay(row.id, "false");
				}
			},
			handleChange(value) {
				console.log(value);
				this.page.currentPage = 1
				this.$refs.crud.toggleSelection();
				let _goodsName = "";
				if(this.query.goodsName){
                    _goodsName = this.query.goodsName;
                }
				this.query = value;
                this.query.goodsName = _goodsName;
				this.onLoad(this.page);
			},

			handleUserChange(value) {
				console.log(value);
				this.page.currentPage = 1
				this.$refs.crud.toggleSelection();
                let _goodsName = "";
                if(this.query.goodsName){
                    _goodsName = this.query.goodsName;
                }
                this.query = value;
                this.query.goodsName = _goodsName;
				this.onLoad(this.page);
			},

			//弹框的取消
			closeDrawer() {
				this.onLoad(this.page)
				this.$refs.stockCrud.resetForm();
				this.$refs.stockCrud.clearValidate();
				
			},
		}
	};
</script>

<style>
	.avue-crud__menu {
		min-height: 0 !important;
		margin-bottom: 0 !important;
	}

	.fromRow[data-v-b476d630] {
		align-items: center;
	}
</style>
